// pages/showcoursevideo/showcoursevideo.js
const db = wx.cloud.database();
const app = getApp();
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    correspondingInfo: "",
    index: "",
    recommend: [],
    isLike: false,
    canTapCollect: true,
  },

  // -------------------------------------------------------------------
  addSee(e) {
    let that = this;
    console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index;
    let course_id = that.data.recommend[index]._id;
    db.collection('userCollect').where({
      _openid: app.personInfo._openid,
      course_id: course_id
    }).get({
      success: res => {
        if (res.data.length == 0) {
          //没点过，现在点
          db.collection('userCollect').add({
            data: {
              type: "访问量",
              _openid: app.personInfo._openid,
              course_id: course_id
            },
            success: res => {
              console.log("成功记录访问者");
            }
          })
          db.collection('course').doc(course_id).update({
            data: {
              see: _.inc(1)
            },
            success: res => {
              that.setData({
                ['recommend[' + index + '].see']: that.data.recommend[index].see + 1,
              });
              console.log('当前课程的点击量：' + that.data.recommend[index].see);
            }
          })
        } else {
          console.log("用户已经访问过这个课程了");
        }
      },
      complete() {
        that.transformationcard(e.currentTarget.dataset.correspondinginfo);
      }
    })
  },


  transformationcard(correspondinginfo) {
    getApp().navTmpInfo = correspondinginfo;

    wx.navigateTo({
      url: "/pages/videocard/videocard"
    })
  },
  getBackclass() {
    wx.navigateBack({
      delta: 1,
    })
  },
  getBackallcatalog() {
    getApp().navTmpInfo = this.data.correspondingInfo;
    wx.navigateTo({
      url: "/pages/videocard/videocard"
    })
  },
  // 上一节事件
  getBackcatalog() {
    let that = this;
    // 判断临界
    if (this.data.index == 0) {
      wx.showToast({
        icon: "none",
        title: '当前是第一节',
      })
    } else { //非临界，才上一节
      let index = this.data.index - 1;
      let obj = {
        correspondinginfomation: that.data.correspondingInfo,
        index: index
      };
      app.navTmpInfo = obj;
      wx.navigateTo({
        url: '/pages/showcoursevideo/showcoursevideo',
      })
    }
  },
  // 下一节事件
  nextSection() {
    // 判断临界
    if (this.data.correspondingInfo.catalog.length - 1 == this.data.index) {
      wx.showToast({
        icon: "none",
        title: '当前是最后一节',
      })
    } else { // 非临界才下一节
      let obj = {
        correspondinginfomation: this.data.correspondingInfo,
        index: this.data.index + 1
      }
      app.navTmpInfo = obj;
      wx.navigateTo({
        url: '/pages/showcoursevideo/showcoursevideo',
      });
    }

  },

  //点赞
  collectLike() {
    let that = this;
    // 先判断是否允许点赞
    if (that.data.canTapCollect == false) {
      wx.showToast({
        icon: "none",
        title: '操作频繁',
      })
      return;
    }

    // 没点赞，现在点赞
    if (that.data.isLike == false) {
      that.setData({
        isLike: true
      });
      db.collection('userCollect').add({
        data: {
          type: '点赞',
          uuid: that.data.correspondingInfo._id
        },
        success: res => {
          console.log(res);
        },
        fail: res => {
          console.log(res);
        }
      })
    } else {
      // 点赞了，现在取消点赞
      that.setData({
        isLike: false
      });
      db.collection('userCollect').where({
        _openid: app.personInfo._openid,
        type: '点赞',
        uuid: that.data.correspondingInfo._id
      }).remove();
    }

    // 不允许再点击
    this.setData({
      canTapCollect: false
    })
    // 防止频繁操作的定时器
    // N秒后再允许点击
    setTimeout(() => {
      that.setData({
        canTapCollect: true
      });
    }, 2000);

  },
  // -------------------------------------------------------------
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    console.log(app.navTmpInfo);
    this.setData({
      correspondingInfo: app.navTmpInfo.correspondinginfomation,
      index: app.navTmpInfo.index
    })
    // if (!Object.keys(app.navTmpInfo).length) {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '异常',
    //   });
    //   return;
    // }

    // this.setData({
    //   correspondingInfo: app.navTmpInfo
    // })
    // console.log(this.data.correspondingInfo);

    // //查询用户是否有点赞这个课程
    // db.collection('userCollect').where({
    //   _openid: app.personInfo._openid,
    //   uuid: that.data.correspondingInfo._id
    // }).get({
    //   success: res => {
    //     if (res.data.length != 0) {
    //       that.setData({
    //         isLike: true
    //       })
    //     }
    //   },
    //   fail: res => {
    //     console.log(res);
    //   }
    // })
    db.collection('userCollect').where({
      _openid: app.personInfo._openid,
      type: "点赞",
      uuid: that.data.correspondingInfo._id
    }).get({
      success: res => {
        if (res.data.length == 0) {
          that.setData({
            isLike: false
          });
          console.log("用户未点赞此课程")
        } else {
          that.setData({
            isLike: true
          })
          console.log("用户已点赞此课程")
        }
      }
    })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    console.log("onshow");
    db.collection('course').limit(4).orderBy('see', 'desc').get({
      success: res => {
        that.setData({
          recommend: res.data
        });
        console.log(that.data.recommend);
      },
      fail: res => {
        console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})